<template>
  <yd-ls-box>
    <yd-ls-layout :title="titles" :onfoot=false :tolfurl="urls">
      <div class="yd-ls-height"></div>
      <div class="yd-ls-waming" v-if="applyInfo.remark!=''">
        {{ applyInfo.remark }}
      </div>
      <yd-list theme="4" class="yd-ls-apply-title-box">
        <yd-list-item >
          <img slot="img" :src="applyInfo.head || defalut_img">
          <span slot="title">
            <span>{{ applyInfo.doctor_name }}</span>
            <span style="color: red;">{{ applyInfo.pay_money }}元/次</span>
          </span>
          <yd-list-other slot="other">
            <div>{{ applyInfo.cust_name }} | {{ applyInfo.title }} <div>&nbsp;</div></div>
            <div style="text-align:right">
              <s v-if="applyInfo.discount_money">{{ applyInfo.discount_money }}元/次</s>
              <!-- <div>&nbsp;</div> -->
              <div v-if="!applyInfo.discount_money">&nbsp;</div>
            </div>
          </yd-list-other>
        </yd-list-item>
      </yd-list>

      <yd-cell-group>
        <yd-cell-item class="yd-ls-billcase-cell-list yd-ls-billcase-cell-details">
          <span slot="left" style="font-weight: 800;">联系人电话</span>
        </yd-cell-item>
        <div class="yd-ls-billcase-details" >
            <p>
              <yd-input slot="right" v-model="tel" ref="tel" required regex="mobile" :onBlur="checkNo" placeholder="请输入手机号码"></yd-input>
              <!--<input type="tel" pattern="[0-9]*" maxlength="11" v-model="tel" @blur="checkNo($event)" placeholder="请输入手机号码" autocomplete="off">-->
            </p>
        </div>
        <yd-cell-item class="yd-ls-billcase-cell-list yd-ls-billcase-cell-details" style="height: .6rem" v-if="showCode">
          <span slot="left" style="color: red;font-weight: 100">您填写的不是注册号码，请先验证</span>
        </yd-cell-item>
        <div class="yd-ls-billcase-details" v-if="showCode">
          <p>
            <input type="text" maxlength="6" v-model="code" slot="right" placeholder="请输入验证码">
            <yd-sendcode
              slot="right"
              @click.native="sendCode"
              type="warning"
              v-model="incode"
              style="float: right;"></yd-sendcode>
          </p>
        </div>
        <yd-cell-item class="yd-ls-billcase-cell-list yd-ls-billcase-cell-details">
          <span slot="left" style="font-weight: 800;">期望预约时间</span>
        </yd-cell-item>
        <div class="yd-ls-billcase-details" >
          <p>
            <yd-datetime 
            :startDate="sDate" 
            ref="datetime" 
            :initEmit="false" 
            v-model="datetimes" 
            placeholder="请选择期望预约时间" 
            @click.native="openDatetime">
            </yd-datetime>
            <!-- <input 
              type="text"
              unselectable="on"
              onfocus="this.blur()"
              placeholder="请选择期望预约时间" 
              v-model="datetimes" 
              readonly 
              @click="openDatetime"> -->
          </p>
        </div>
        <yd-cell-item class="yd-ls-billcase-cell-list yd-ls-billcase-cell-details">
          <span slot="left" style="font-weight: 800;">病情描述</span>
        </yd-cell-item>
        <div class="yd-ls-billcase-details" @click="popupdetail">
          <p>
            <input
              type="text"
              unselectable="on"
              onfocus="this.blur()"
              style="width: 100%;"
              v-if="!details"
              readonly placeholder="填写症状表现、检查结果、用药和希望获得的帮助">
            {{ details }}
          </p>
        </div>
        <yd-cell-item class="yd-ls-billcase-cell-list yd-ls-billcase-cell-details">
          <span slot="left" style="font-weight: 800;">相关图片</span>
          <span slot="right">(上传与病情相关的病历等图片，限3张)</span>
        </yd-cell-item>
        <div class="yd-ls-billcase-details" >
          <p>
            <yd-lightbox :num="imgItems.length">
              <yd-grids-group :rows="3"  class="yd-ls-photo-list">

                <yd-grids-item  v-for="(items, index) in imgItems" :key="index">
                  <yd-lightbox-img slot="icon" :src="items"></yd-lightbox-img>
                  <yd-icon slot="text" size=".4rem" color="#FF685D" style="background-color:#fff;border-radius:.4rem" name="shanchu" @click.native="delPic(index)" custom></yd-icon>
                </yd-grids-item>

                <yd-grids-item  @click.native="addPic" v-if="imgItems.length<3" style="width:22%;">
                  <yd-icon slot="icon" size=".8rem" color="#FF685D" name="kttx" custom></yd-icon>
                </yd-grids-item>
              </yd-grids-group>
            </yd-lightbox>
          </p>
        </div>

      </yd-cell-group>

      <yd-ls-title lftit="温馨提示" rgtit=""></yd-ls-title>
      <yd-ls-content>
        <div slot="content">
          <ul>
            <li>1、提交申请不用付款，仅作为向医生发起预约请求。</li>
            <li>2、申请通过或失败后会在{{comName}}公众号上通知，请留意信息。</li>
            <li v-if="visitType == 3">3、具体线下面诊地点需与医生确认后再通过公众号或短信通知。</li>
          </ul>
        </div>
      </yd-ls-content>

      <!--展示 病情描述-->
      <yd-popup v-model="showdetail" position="right" width="100%">
        <yd-ls-popup-header headname="病情描述" btnname="确定" @handle-popup-back="popupback" @handle-popup-button="comfdetails"></yd-ls-popup-header>

        <yd-cell-group>
          <yd-cell-item>
            <yd-textarea slot="right" placeholder="填写症状表现、检查结果、用药和希望获得的帮助" maxlength="100" v-model="details"></yd-textarea>
          </yd-cell-item>
        </yd-cell-group>
      </yd-popup>
      <div class="yd-ls-height"></div>
    </yd-ls-layout>
    <yd-ls-button btnname="提交申请" @handle-button="apply"></yd-ls-button>
  </yd-ls-box>
</template>

<style>

  .yd-ls-billcase-cell-details:not(:last-child):after {
    height: 0;
  }
  .yd-ls-billcase-details {
    padding-left: .24rem;
    line-height: .6rem;
    color: #555;
  }
  .yd-ls-billcase-details:after {
    display: block;
    content: "";
    width: 100%;
    font-size: .3rem;
    border-bottom: 1px solid #d9d9d9;
    -webkit-transform: scaleY(.5);
    transform: scaleY(.5);
    -webkit-transform-origin: 0 0;
    transform-origin: 0 0;
  }
  .yd-ls-billcase-details input {
    border: 0;
  }
  .yd-ls-billcase-details p {
    padding: 0 .1rem;
    padding-bottom: .2rem;
    line-height: .4rem;
  }
  .yd-ls-billcase-cell-list .yd-cell-left span:nth-child(2) {
    padding-right: .48rem;
    font-weight: 600;
  }
  .yd-ls-billcase-cell-details .yd-cell-left span:nth-child(2) {
    padding-right: .1rem
  }
  .yd-ls-billcase-cell-list .yd-cell-right {
    justify-content: flex-start;
    -webkit-justify-content: flex-start;
  }

  .yd-ls-accountapply-cell-group {
    margin-bottom: 0;
  }
  .yd-ls-accountapply-cell-group .yd-ls-accountapply-cell-details:not(:last-child):after {
    border-bottom: 0;
  }
  .yd-ls-accountapply-details {
    padding-left: .24rem;
    line-height: .6rem;
    color: #555;
  }
  .yd-ls-accountapply-details:after {
    display: block;
    content: "";
    width: 100%;
    font-size: .3rem;
    border-bottom: 1px solid #d9d9d9;
    -webkit-transform: scaleY(.5);
    transform: scaleY(.5);
    -webkit-transform-origin: 0 0;
    transform-origin: 0 0;
  }
  .yd-ls-accountapply-details input {
    border: 0;
  }
  .yd-ls-accountapply-cell .yd-cell-left span:nth-child(2) {
    width: 50px;
    text-align: right;
  }
  .yd-ls-accountapply-cell-item .yd-cell-left span:nth-child(2) {
    padding-right: .48rem
  }
  .yd-ls-accountapply-cell-details .yd-cell-left span:nth-child(2) {
    padding-right: .1rem
  }

  .yd-ls-apply-title-box.yd-list {
    padding: 0;
  }
  .yd-ls-apply-title-box.yd-list .yd-list-item {
    padding: 0.2rem 0.3rem;
    line-height: initial;
  }
  .yd-ls-apply-title-box.yd-list .yd-list-item .yd-list-img {
    width: 1.2rem;
    padding: 0.6rem 0;
    border-radius: 50%;
    margin-right: 0.2rem;
  }
  .yd-ls-apply-title-box.yd-list .yd-list-item .yd-list-mes {
    padding-top: 10px;
  }
  .yd-ls-apply-title-box.yd-list .yd-list-item .yd-list-mes .yd-list-other {
    padding-top: 0;
  }
  .yd-ls-apply-title-box.yd-list .yd-list-item .yd-list-title {
    padding-bottom: .1rem
  }
  .yd-ls-apply-title-box.yd-list .yd-list-item .yd-list-title span span:last-child{
    float: right;
    font-size: 12px;
    color: #919191;
    font-weight: normal;
  }
  .yd-ls-apply-title-box.yd-list .yd-list-item .yd-list-other p {
    padding-bottom: .05rem
  }
  .yd-ls-apply-title-box.yd-list .yd-list-item .yd-list-other .yd-ls-subscribe-address{
    width: 4rem;
    text-overflow:ellipsis;
    overflow:hidden;
    white-space:nowrap;
  }
  .yd-ls-apply-title-box.yd-list .yd-list-item .yd-list-mes .yd-list-title {
    font-size: .28rem;
  }
  .yd-ls-apply-title-box.yd-list {
    border-bottom: 2px solid #d9d9d9;
  }
</style>
<script>
  import ydLsBox from '../../components/yd-ls-box.vue'
  import ydLsLayout from '../../components/yd-ls-layout.vue'
  import ydLsPopupHeader from '../../components/yd-ls-popup-header.vue'
  import ydLsTitle from '../../components/yd-ls-title.vue'
  import ydLsContent from '../../components/yd-ls-content.vue'
  import ydLsButton from '../../components/yd-ls-button.vue'
  import wx from 'wx'
  import api from '../../axios/api'

  export default {
    name: 'assay',
    props: {},
    data () {
      return {
        urls: '',
        comName: api.default_title,
        titles: '预约申请',
        drId: '',
        visitId: '',
        tel: '',
        oldTel: '', // 保存原始手机号码
        showCode: false, // 输入新手机号码时，显示验证
        time: '',
        code: '',
        incode: false,
        assayitems: [],
        datetimes: '',
        details: '',
        olddetails: '',
        isdetails: false,
        showdetail: false,
        openID: '', // 获取身份ID
        viewpic: false,
        is_conf: false, // 未上传图片时，上传按钮不能用
        firstTime: false, // 是否第一次进入
        firstUpload: false, // 是否第一次上传
        imgItems: [], // 图片数组
        serverIds: [], // 存储多图的serverId
        applyInfo: {},
        sDate: '2018-01-01', // 预约开始时间
        visitType: sessionStorage.vType,
        defalut_img: api.default_img_dot // 医生缺省头像
      }
    },
    created() {
      //TODO:微信图片上传--页面验证
      this.$dialog.loading.open(api.default_loading_txt);
      const getWxValid = ()=>{
        this.axios({
          method:'get',
          url:api.wx_valid,
          params:{
            pageurl: window.location.href
          }
        }).then(function(rsp) {
            wxconfig(rsp.data)
          }).catch(err=>{
            this.$dialog.loading.close()
            this.$dialog.alert({mes: JSON.stringify(err)})
          })
      }
      const wxconfig = (datas)=>{
        wx.config({
          debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
          appId: datas.appId, // 必填，公众号的唯一标识
          nonceStr: datas.nonceStr, // 必填，生成签名的随机串
          timestamp: datas.timestamp, // 必填，生成签名的时间戳
          signature: datas.signature, // 必填，签名，见附录1
          jsApiList: [
            'checkJsApi',
            'chooseImage',
            'previewImage',
            'uploadImage',
            'downloadImage',
            'translateVoice'
          ] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
        });
      }
      wx.hideMenuItems({
        menuList: ["menuItem:share:appMessage","menuItem:share:timeline","menuItem:share:qq","menuItem:share:weiboApp","menuItem:share:facebook","menuItem:share:QZone","menuItem:copyUrl","menuItem:originPage","menuItem:openWithQQBrowser","menuItem:openWithSafari"] // 要隐藏的菜单项，只能隐藏“传播类”和“保护类”按钮，所有menu项见附录3
      });

      getWxValid()

      //TODO:初始化数据
      this.serverIds.length = 0; // 初始化
      let vid = sessionStorage.vId
      this.titles = `${sessionStorage.vName}预约申请`
      this.getApplyBase(vid)
    },
    methods: {
      checkNo(ev) {
        let _this = this
        const userPhone = this.$refs.tel
        if(!userPhone.valid) {
          this.notify('请先填写正确的11位数手机号码！')
          this.tel = ''
          userPhone.setFocus();
          return
        }

        if(this.oldTel != this.tel) {
          this.showCode = true
          this.code = ''
          return
        }else {
          this.showCode = false
          this.code = ''
          return
        }
      },
      openDatetime() {
        let nowDate = parseInt(new Date().valueOf())+3600000;
        this.sDate = new Date(nowDate).format("yyyy-MM-dd hh:mm")
        setTimeout(()=>{
          this.$refs.datetime.open()
        },100)

      },
      getApplyBase(vid) {
        this.axios.get(api.seek_apply_info, {params: {visit_id: vid}})
          .then(m=>{
            let apply_info_data = m.data
            this.$dialog.loading.close()

            this.applyInfo = apply_info_data.data
            this.tel = this.applyInfo.answer_tel
            this.oldTel = this.applyInfo.answer_tel
            this.drId = this.applyInfo.drid
            this.visitId = this.applyInfo.visit_id

            let vform =sessionStorage.vForm
            if(vform=="seek"){
              this.urls = `seek.html`
            }else{
              this.urls = `index.html#/${vform}?drid=${this.drId}`
            }
          }).catch(err=>{
            this.$dialog.loading.close()
            this.$dialog.alert({mes: JSON.stringify(err)})
          })
      },
      apply () {
        if(this.tel=='' || this.tel.length<11) {
          this.notify('请先填写正确的11位数手机号码！')
          return
        }
        if(this.showCode && !!!this.code) {
          this.notify('请先填写验证码再提交申请！')
          return
        }
        if(!!!this.datetimes || this.datetimes==='请选择期望预约时间') {
          this.notify('请选择期望预约时间！')
          return
        }
        if(!!!this.details) {
          this.notify('请填写病情描述后再提交申请！')
          return
        }
        //是否添加了图片
        let len = this.imgItems.length
        if(len > 0){
          this.upload()
          return
        }else {
          this.submitApply()
        }
        
      },
      submitApply() {
        
        let _this = this
        let params = {
                answer_tel: _this.tel,
                valid_code: _this.code,
                expect_date: _this.datetimes.split(' ')[0],
                expect_time: _this.datetimes.split(' ')[1],
                disease_des: _this.details,
                files: _this.serverIds,
                visit_id: _this.visitId,
                drid: _this.drId,
                visit_type: sessionStorage.vType
              }
              _this.$dialog.loading.open(api.default_loading_txt);
              _this.axios.post(api.seek_apply_submit,params)
                .then(m=>{
                  _this.$dialog.loading.close()
                  if (m.data.retcode != 0) {
                    _this.notify(m.data.retmsg)
                    return;
                  }
                  sessionStorage.isTab = sessionStorage.vType*1 - 2
                  sessionStorage.getSubscribeId = m.data.data
                  window.location = 'subscribedetail.html#/'
                }).catch(err=>{
                  _this.$dialog.loading.close()
                  _this.$dialog.alert({mes: JSON.stringify(err)})
                })
      },
      notify(info) {
        this.$dialog.notify({
          mes: info,
          timeout: 1500
        });
      },
      popupdetail() {
        if(!this.details){
          this.isdetails = true
        }else {
          this.isdetails = false
        }
        this.showdetail = true
      },
      popupback() {
        if(this.isdetails && !this.olddetails){
          this.details = ''
        }else{
          this.details = this.olddetails
        }
        this.showdetail = false
      },
      comfdetails() {

        if(!!!this.details) {
          this.notify('请填写病情描述后再提交申请！')
          return
        }
        this.olddetails = this.details
        this.showdetail = false
      },
      sendCode() {

        if(!!!this.tel) {
          this.notify('请先填写正确的11位数手机号码！')
          return
        }

        this.$dialog.loading.open('发送中...');
        this.axios.get(api.base_code,{
          params: {
            mobileno: this.tel
          }
        }).then(m=>{
          this.$dialog.loading.close();
          this.incode = true
          this.notify('已发送，请查收！')
        }).catch(err=>{
          this.$dialog.loading.close();
          this.notify('发送失败，请重发！')
        })
      },
      addPic(id) {
        let _this = this
        let len = _this.imgItems.length
        if(len === 3 ){
          _this.$dialog.alert({mes: '最多仅允许上传3张图片！'});
          return
        }
        wx.chooseImage({
          count: 3 - len, // 默认9
          sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
          sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
          success: function(res) {
            let localIds = res.localIds; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
            _this.imgItems = _this.imgItems.concat(localIds)
          },
          fail: function (res) {
            _this.$dialog.alert({mes: JSON.stringify(res)});
          }
        });

      },
      upload() {
        let _this = this
        var localId = _this.imgItems.pop();
        wx.uploadImage({
          localId: localId,
          isShowProgressTips: 1,
          success: function (res) {
            _this.serverIds.push(res.serverId)
            if(_this.imgItems.length > 0){
              _this.upload();
            }else{
              _this.submitApply()
            }
          },
          fail: function (res) {
            _this.$dialog.alert({mes:JSON.stringify(res)})
          }
        });
      },
      delPic(index) {
        this.imgItems.splice(index, 1)
      }
    },
    mounted() {},
    components: { ydLsBox, ydLsLayout, ydLsPopupHeader, ydLsTitle, ydLsContent, ydLsButton }


  }
</script>

